package com.gin.kotlin.no_gay_alliance.adapter.reply

import android.annotation.SuppressLint
import android.app.Activity
import android.view.View
import android.widget.CompoundButton
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.adapter.post.UploadedAttachmentAdapter.Companion.configAttachmentImageView
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.DownloadUtils
import com.gin.kotlin.no_gay_alliance.base.GlideModule.Companion.CROSS_FADE
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.base.PhotoPreviewUtils
import com.gin.kotlin.no_gay_alliance.databinding.ItemAttachmentBinding
import com.gin.kotlin.no_gay_alliance.listener.PhotoPreviewLongClickListener
import com.gin.kotlin.no_gay_alliance.model.AttachmentModel
import com.gin.nga.enums.ImageThumb

class AttachmentAdapter(context: Activity, handler: MyHandler) : AbstractBindingRecyclerViewAdapter<ItemAttachmentBinding, AttachmentModel>(context, handler),
    View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    override fun onBindViewHolder(holder: ViewHolder<ItemAttachmentBinding>, position: Int, b: ItemAttachmentBinding, dataModel: AttachmentModel) {
        b.tvAttachSize.text = "${dataModel.size} KB"
        b.tvAttachDescription.text = dataModel.description?.takeIf { it.isNotEmpty() } ?: "<无描述>"
        b.tvOriginalFilename.text = dataModel.originalFilename?.takeIf { it.isNotEmpty() } ?: "<无文件名>"

        configAttachmentImageView(b.ivAttachment, dataModel.extension) {
            Glide.with(context)
                .load(dataModel.getUrl(dataModel.getImageThumbs()[0]))
                .error(R.drawable.ic_image_24)
                .placeholder(R.drawable.ic_image_24)
                .transition(DrawableTransitionOptions.withCrossFade(CROSS_FADE))
                .into(it)
        }

        listOf(b.ivAttachment).forEach {
            it.tag = dataModel
            it.setOnClickListener(this)
        }

        b.checkBox.setOnCheckedChangeListener(null)
        b.checkBox.isChecked = dataModel.isChecked
        b.checkBox.tag = dataModel
        b.checkBox.setOnCheckedChangeListener(this)
    }

    override fun onClick(v: View?) {
        val dataModel = v?.tag as? AttachmentModel ?: return

        when (v.id) {
            // 图片才预览
            R.id.iv_attachment -> if (!dataModel.isImage)
                handler.toast(context.getString(R.string.toast_message_preview_image_only))
            else {
                val list = data.filter { it.isImage }
                PhotoPreviewUtils.build(
                    context as FragmentActivity,
                    list.mapNotNull { it.getUrl(ImageThumb.ORIGINAL) },
                    listener = PhotoPreviewLongClickListener(context) { position ->
                        run {
                            val attachmentModel = data[position]
                            PhotoPreviewLongClickListener.PreviewImage(attachmentModel.getUrl()!!, attachmentModel.getBbsCode()!!)
                        }
                    }
                )
                    .defaultShowPosition(list.indexOf(dataModel)).build().show(v)
            }

        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun unselectAll() {
        data.forEach { it.isChecked = false }
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun selectAll() {
        data.forEach { it.isChecked = true }
        notifyDataSetChanged()
    }

    /**
     * 下载选中的附件
     */
    fun downloadSelected() {
        val selected = data.filter { it.isChecked }
        if (selected.isEmpty()) {
            handler.toast("没有选中任何附件")
            return
        }
        DownloadUtils.enqueue(context, selected.map { it.obtainDownloadOption() })
        handler.toast("已开始下载 ${selected.size} 个附件")
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        val attachmentModel = buttonView?.tag as AttachmentModel
        attachmentModel.isChecked = isChecked
    }
}